#include "HerzeleidPrecompiled.hxx"
#include "HerzeleidCoreDispatcher.hxx"

using namespace HerzeleidUICoreNamespaceImpl;

CoreDispatcher::~CoreDispatcher()
{
	PrintToDebugWindowOnly8("Herzeleid. Deleting window dispatcher.");
	DiscardAll();

	//switch ( m_eClosingOption )
	//{
	//case CoreDispatcherClosingOption::DiscardAllIfAny: 
	//	{
	//		PrintToDebugWindowOnly8("Herzeleid. Discard all captured window events.");
	//		DiscardAll();
	//	} break;
	//case CoreDispatcherClosingOption::ProcessAllIfAny:
	//	{
	//		PrintToDebugWindowOnly8("Herzeleid. Process all captured window events.");

	//		try
	//		{
	//			// First, we should stop catching messages. 
	//			AutoDebugVariable( CapturingTaskStatus )	m_MsgCapturing.wait(); // Wait until the task is finished.
	//			AutoDebugVariable( CapturingTaskResult )	m_MsgCapturing.get(); // Get the task results.

	//			// Then, we should terminate message dispatching task chain. 
	//			AutoDebugVariable( DispatchingTaskStatus )	m_MsgDispatching.wait(); // Wait until the task is finished.
	//			AutoDebugVariable( DispatchingTaskResult )	m_MsgDispatching.get(); // Get the task results.
	//		}
	//		catch ( AsyncActionCanceledErrorConstRef Error )
	//		{
	//			// Most likely, we wont reach this point, until the get() function is called. 
	//			PrintToDebugWindowOnly8( Error.what() );
	//		}
	//		catch ( ErrorConstRef Error )
	//		{
	//			// The exceptions, that were raised while the task dispatching should appear here. 
	//			// And we want to know "what()" exactly happend. 
	//			PrintToDebugWindowOnly8( Error.what() );
	//		}

	//		// Dispatch all the pending message immediately. 
	//		while (!m_Messages.empty())
	//		{
	//			WindowMessage Message;
	//			if (m_Messages.try_pop(Message))
	//			{
	//				Process(Message);
	//			}
	//		}
	//	} break;
	//}
}

void CoreDispatcher::DiscardAll()
{
	try
	{
		// First, we should stop catching messages. 
		m_CancellationTokenSrcForCapturing.cancel(); // Cancel task. 
		AutoDebugVariable( CapturingTaskStatus )	m_MsgCapturing.wait(); // Wait until the task is cancelled.

		// Then, we should terminate message dipatching task chain. 
		m_CancellationTokenSrcForDispatching.cancel(); // Cancel task. 
		AutoDebugVariable( DispatchingTaskStatus )	m_MsgDispatching.wait(); // Wait until the task is cancelled.
	}
	catch ( AsyncActionCanceledErrorConstRef Error )
	{
		// Most likely, we wont reach this point, until the get() function is called. 
		PrintToDebugWindowOnly8( Error.what() );
	}
	catch ( ErrorConstRef Error )
	{
		// The exceptions, that were raised while the task execution should appear here. 
		// And we want to know "what()" exactly happend. 
		PrintToDebugWindowOnly8( Error.what() );
	}
}